package icu.zlz.message.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.mail.SimpleMailMessage;

/**
 * 邮件发送服务
 */
@Service
public class EmailService {
    private final JavaMailSender primaryJavaMailSender;
    private final JavaMailSender secondaryJavaMailSender;


    @Autowired
    public EmailService(@Qualifier("primaryJavaMailSender") JavaMailSender primaryJavaMailSender,
                        @Qualifier("secondaryJavaMailSender") JavaMailSender secondaryJavaMailSender) {
        this.primaryJavaMailSender = primaryJavaMailSender;
        this.secondaryJavaMailSender = secondaryJavaMailSender;
    }

    public void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        try {
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);
            primaryJavaMailSender.send(message);
            System.out.println("Email sent successfully using primary server.");
        } catch (Exception e) {
            System.err.println("Failed to send email using primary server. Trying secondary server...");
            try {
                secondaryJavaMailSender.send(message);
                System.out.println("Email sent successfully using secondary server.");
            } catch (Exception ex) {
                System.err.println("Failed to send email using secondary server.");
                ex.printStackTrace();
            }
        }
    }
}
